import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { FetchService } from '../../../core/net/fetch.service';
import * as moment from 'moment';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-pm-maintain',
  templateUrl: './pm-maintain.component.html',
  styleUrls: ['./pm-maintain.component.scss']
})
export class PmMaintainComponent implements OnInit {

    searchForm: FormGroup;
    statusTypeList: Array<{ label: string, value: string | number }>;
    statusMapper;
    originList: Array<{ label: string, value: string | number }>;
    originMapper;
    resultTypeList: Array<{ label: string, value: string | number }>;
    resultMapper;
    staffList: Array<{ name: string, id: string | number }>;
    projectList: Array<{ name: string, id: string | number }>;
    tableData = [];
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = false;
    checkForm: FormGroup;
    modalTitle: string = '';
    modalShow: boolean = false;

    pieChartOption = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        color: ['#637efe', '#ffc209', '#0094f0', '#d2e2ff'],
        legend: {
            bottom: 0,
            data: []
        },
        series: [
            {
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: [],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    countInfoChartOpt;
    areaInfoChartOpt;
    projectInfoChartOpt;
    sourceInfoChartOpt;

    constructor(private fb: FormBuilder,
                private message: NzMessageService,
                private fetchService: FetchService) {
    }

    ngOnInit(): void {
        this.searchForm = this.fb.group({
            rangePickerTime: [[moment().subtract(1, 'months').startOf('month').valueOf(), new Date()]],
            // source: [],
            // state: [],
            // manageName: []
            keywords: []
        });
        this.checkForm = this.fb.group({
            taskid: '',
            objid: [null, Validators.required],
            source: [null, Validators.required],
            staffid: [null, Validators.required],
            manageName: [null, Validators.required],
            taskname: [null, Validators.required],
            taskdesc: [null, Validators.required],
            begindate: [null, Validators.required],
            enddate: [null, Validators.required],
            state: [null, Validators.required],
            resultstate: [null, Validators.required],
            result: [null, Validators.required]
        });
        //  人员列表查询
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {
            apicode: '15',
            manageId: '1'
        }).subscribe(res => {
            if (Array.isArray(res)) {
                this.staffList = res;
            }
        });
        //  工程列表查询
        this.fetchService.post<any>('archives/wrsProjectInfo/list', {
            pageSize: 10000
        }).subscribe(res => {
            this.projectList = res['list'] || [];
            this.projectList.forEach(item => {
                item.id = item.id + '';
            });
        });
        // 10018 状态
        // 10019 结果状态
        // 10021 维修来源
        this.getDictValue('10018').subscribe(res => {
            this.statusTypeList = res.list;
            this.statusMapper = res.mapper;
        });
        this.getDictValue('10019').subscribe(res => {
            this.resultTypeList = res.list;
            this.resultMapper = res.mapper;
        });
        this.getDictValue('10021').subscribe(res => {
            this.originList = res.list;
            this.originMapper = res.mapper;
        });

        this.queryInfo();
    }

    getDictValue(typeId) {
        return this.fetchService
            .post<any>('sys/sysDictValue/list', {
                dictTypeId: typeId
            })
            .pipe(
                map(res => {
                    const list = res['list'] || [];
                    const mapper = list.reduce((def, item) => {
                        def[item.value] = item.label;
                        return def;
                    }, {});
                    return {
                        list,
                        mapper
                    };
                })
            );
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        this.loading = true;
        const params = {
            ...this.searchForm.value,
            begindate: this.searchForm.get('rangePickerTime').value[0] ? moment(this.searchForm.get('rangePickerTime').value[0]).format('YYYY-MM-DD') : null,
            enddate: this.searchForm.get('rangePickerTime').value[1] ? moment(this.searchForm.get('rangePickerTime').value[1]).format('YYYY-MM-DD') : null,
            pageNum: this.pageNum,
            pageSize: this.pageSize
        };
        this.fetchService.post('projectManage/wxTask/list', params).subscribe(res => {
            this.tableData = res['list'];
            this.total = res['total'];
            this.loading = false;
        });
        // this.queryKpiData();
    }

    queryKpiData(): void {
        //  kpi查询
        this.fetchService.post<any>('projectManage/wxTask/kpi', {
            begindate: this.searchForm.get('rangePickerTime').value[0] ? moment(this.searchForm.get('rangePickerTime').value[0]).format('YYYY-MM-DD') : null,
            enddate: this.searchForm.get('rangePickerTime').value[1] ? moment(this.searchForm.get('rangePickerTime').value[1]).format('YYYY-MM-DD') : null
        }).subscribe(res => {
            this.countInfoChartOpt = {
                legend: {
                    data: Object.keys(res['countInfo'])
                },
                series: [
                    {
                        name: '执行情况',
                        data: Object.keys(res['countInfo']).map(key => {
                            return {
                                value: res['countInfo'][key],
                                name: key
                            };
                        })
                    }
                ]
            };
            this.sourceInfoChartOpt = {
                legend: {
                    data: Object.keys(res['sourceInfo'])
                },
                series: [
                    {
                        name: '任务来源',
                        data: Object.keys(res['sourceInfo']).map(key => {
                            return {
                                value: res['sourceInfo'][key],
                                name: key
                            };
                        })
                    }
                ]
            };
            this.projectInfoChartOpt = {
                legend: {
                    data: Object.keys(res['projectInfo'])
                },
                series: [
                    {
                        name: '故障类型',
                        data: Object.keys(res['projectInfo']).map(key => {
                            return {
                                value: res['projectInfo'][key],
                                name: key
                            };
                        })
                    }
                ]
            };
            this.areaInfoChartOpt = {
                legend: {
                    data: Object.keys(res['areaInfo'])
                },
                series: [
                    {
                        name: '任务地区',
                        data: Object.keys(res['areaInfo']).map(key => {
                            return {
                                value: res['areaInfo'][key],
                                name: key
                            };
                        })
                    }
                ]
            };
        });
    }
    openEditModal(item?): void {
        this.modalTitle = item ? `编辑维护任务` : '新增维护任务';
        this.checkForm.patchValue(item || {});
        this.modalShow = true;
    }

    onDelete(id) {
        this.fetchService.get(`projectManage/wxTask/remove/${id}`).subscribe(resp => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    onConfirm() {
        if (!this.checkForm.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = {
            ...this.checkForm.value,
            begindate: this.checkForm.get('begindate').value ? moment(this.checkForm.get('begindate').value).format('YYYY-MM-DD') : null,
            enddate: this.checkForm.get('enddate').value ? moment(this.checkForm.get('enddate').value).format('YYYY-MM-DD') : null
        };
        const url = data.taskid ? 'projectManage/wxTask/edit' : 'projectManage/wxTask/add';
        this.fetchService.post(url, data).subscribe(res => {
            this.message.success('提交成功');
            this.modalShow = false;
            this.queryInfo();
            this.checkForm.reset();
        });
    }

    onCancel() {
        this.modalShow = false;
        this.checkForm.reset();
    }
}
